<template>
  <div class="v-b">
    <video ref="eVideo" class="v" controls autoplay @ended="onEnded" />
  </div>
</template>

<script>
import ajaxApi from '@/view/ajax-api/index.js'
export default {
  props: {
    d: {
      type: Object,
      default: () => { return {} }
    }
  },
  data () {
    return {
      index: 0,
      videos: []
    }
  },
  computed: {
    eVideo () {
      return this.$refs.eVideo
    },
    dVideos () {
      return this.d.videos
    },
    count () {
      return this.dVideos.length
    },
    allowSound () {
      return this.d.allowSound
    }
  },
  watch: {
    dVideos () {
      this.restart()
    },
    allowSound (allowSound) {
      this.eVideo.muted = !allowSound
    }
  },
  mounted () {
    this.restart()
  },
  methods: {
    restart () {
      if (this.count === 0) {
        this.eVideo.src = ''
        return
      }
      let videos = this.videos = []
      this.dVideos.forEach(v => {
        videos.push(v.src)
      })

      this.play(this.index = 0)
    },
    onEnded () {
      let i = this.index + 1
      if (i >= this.count) this.index = i = 0
      this.play(this.index = i)
    },
    async play (i) {
      let url = this.videos[i]
      let err = await ajaxApi.validityVideoToken(url)
      if (err) {
        this.videos[i] = url = await ajaxApi.getPlayDownloadUrl(url)
      }
      let { eVideo } = this
      eVideo.muted = !this.allowSound
      eVideo.src = url
      eVideo.play()
    }
  }
}
</script>

<style scoped>
.v-b {
  width: 100%;
  height: 100%;
}
.v {
  width: 100%;
  height: 100%;
}
</style>
